package com.dt.platform.oa.service.impl;

import javax.annotation.Resource;

import com.dt.platform.constants.enums.oa.FinPaymentStatusEnum;
import com.dt.platform.domain.oa.*;
import com.dt.platform.oa.service.*;
import com.github.foxnic.commons.lang.StringUtil;
import com.github.foxnic.commons.log.Logger;
import org.github.foxnic.web.session.SessionUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.foxnic.dao.entity.ReferCause;
import com.github.foxnic.commons.collection.MapUtil;

import java.math.BigDecimal;
import java.util.Arrays;


import java.util.List;
import com.github.foxnic.api.transter.Result;
import com.github.foxnic.dao.data.PagedList;
import com.github.foxnic.dao.entity.SuperService;
import com.github.foxnic.dao.spec.DAO;
import java.lang.reflect.Field;
import com.github.foxnic.commons.busi.id.IDGenerator;
import com.github.foxnic.sql.expr.ConditionExpr;
import com.github.foxnic.api.error.ErrorDesc;
import com.github.foxnic.dao.excel.ExcelWriter;
import com.github.foxnic.dao.excel.ValidateResult;
import com.github.foxnic.dao.excel.ExcelStructure;
import java.io.InputStream;
import com.github.foxnic.sql.meta.DBField;
import com.github.foxnic.dao.data.SaveMode;
import com.github.foxnic.dao.meta.DBColumnMeta;
import com.github.foxnic.sql.expr.Select;
import java.util.ArrayList;

import org.github.foxnic.web.framework.dao.DBConfigs;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 付款记录服务实现
 * </p>
 * @author 金杰 , maillank@qq.com
 * @since 2025-06-09 09:21:06
*/


@Service("OaFinPaymentRecordService")

public class FinPaymentRecordServiceImpl extends SuperService<FinPaymentRecord> implements IFinPaymentRecordService {




	@Autowired
	private IFinCollectTicketService finCollectTicketService;


	@Autowired
	private IFinPaymentNoTicketService finPaymentNoTicketService;


	/**
	 * 注入DAO对象
	 * */
	@Resource(name=DBConfigs.PRIMARY_DAO) 
	private DAO dao=null;

	/**
	 * 获得 DAO 对象
	 * */
	public DAO dao() { return dao; }



	@Override
	public Object generateId(Field field) {
		return IDGenerator.getSnowflakeIdString();
	}

	/**
	 * 添加，根据 throwsException 参数抛出异常或返回 Result 对象
	 *
	 * @param finPaymentRecord  数据对象
	 * @param throwsException 是否抛出异常，如果不抛出异常，则返回一个失败的 Result 对象
	 * @return 结果 , 如果失败返回 false，成功返回 true
	 */
	@Override
	public Result insert(FinPaymentRecord finPaymentRecord,boolean throwsException) {


		BigDecimal totalAmount=null;
		BigDecimal paymentAmount=null;
		if("no_ticket".equals(finPaymentRecord.getOwnerType())){
			FinPaymentNoTicket finPaymentNoTicket=finPaymentNoTicketService.getById(finPaymentRecord.getOwnerId());
			paymentAmount=finPaymentNoTicket.getPaymentAmount();
			totalAmount=finPaymentNoTicket.getAmount();
			if(FinPaymentStatusEnum.PART.code().equals(finPaymentNoTicket.getPaymentStatus())
					||FinPaymentStatusEnum.WAIT.code().equals(finPaymentNoTicket.getPaymentStatus())){
				Logger.info("ticket");
			}else{
				return ErrorDesc.failureMessage("当前单据状态无法进行付款操作");
			}
		}else if("ticket".equals(finPaymentRecord.getOwnerType())){
			FinCollectTicket finCollectTicket=finCollectTicketService.getById(finPaymentRecord.getOwnerId());
			paymentAmount=finCollectTicket.getPaymentAmount();
			totalAmount=finCollectTicket.getAmount();
			if(FinPaymentStatusEnum.PART.code().equals(finCollectTicket.getPaymentStatus())
					||FinPaymentStatusEnum.WAIT.code().equals(finCollectTicket.getPaymentStatus())){
				Logger.info("ticket");
			}else{
				return ErrorDesc.failureMessage("当前单据状态无法进行付款操作");
			}
		}else{
			return ErrorDesc.failureMessage("当前类型不正确,类型:"+finPaymentRecord.getOwnerType());
		}

		if(finPaymentRecord.getAmount().compareTo(BigDecimal.ZERO)<=0){
			return ErrorDesc.failureMessage("金额必须大于0");
		}

		if(finPaymentRecord.getAmount().compareTo(totalAmount)>0){
			return ErrorDesc.failureMessage("金额必须小于"+totalAmount+"元");
		}
		finPaymentRecord.setOriginatorId(SessionUser.getCurrent().getActivatedEmployeeId());

		if(finPaymentRecord.getAmount().add(paymentAmount).compareTo(totalAmount)>0){
			return ErrorDesc.failureMessage("总金额为:"+totalAmount+",当前支付总金额:"+finPaymentRecord.getAmount().add(paymentAmount)+",已超额支付");
		}


		//开始更新主要单据
		Result r=super.insert(finPaymentRecord,throwsException);
		if(r.success()){
			if("no_ticket".equals(finPaymentRecord.getOwnerType())){
				FinPaymentNoTicket finPaymentNoTicket=new FinPaymentNoTicket();
				finPaymentNoTicket.setId(finPaymentRecord.getOwnerId());
				finPaymentNoTicket.setPaymentLastDate(new Date());
				finPaymentNoTicket.setPaymentStatus(FinPaymentStatusEnum.PART.code());
				finPaymentNoTicketService.update(finPaymentNoTicket,SaveMode.NOT_NULL_FIELDS);
				//计算
				dao.execute("update oa_fin_payment_no_ticket set payment_amount=ifnull((select sum(amount) from oa_fin_payment_record where deleted=0 and owner_id=?),0)  where id=?",finPaymentRecord.getOwnerId(),finPaymentRecord.getOwnerId());
			}else if("ticket".equals(finPaymentRecord.getOwnerType())){
				FinCollectTicket finCollectTicket=new FinCollectTicket();
				finCollectTicket.setId(finPaymentRecord.getOwnerId());
				finCollectTicket.setPaymentTime(new Date());
				finCollectTicket.setPaymentStatus(FinPaymentStatusEnum.PART.code());
				finCollectTicketService.update(finCollectTicket,SaveMode.NOT_NULL_FIELDS);
				//计算
				dao.execute("update oa_fin_collect_ticket set payment_amount=ifnull((select sum(amount) from oa_fin_payment_record where deleted=0 and owner_id=?),0)  where id=?",finPaymentRecord.getOwnerId(),finPaymentRecord.getOwnerId());
			}
		}

		return r;
	}

	@Override
	public Result action(String id, String actionType,String ownerType) {

		if ("no_ticket".equals(ownerType)) {
			dao.execute("update oa_fin_payment_no_ticket set payment_amount=ifnull((select sum(amount) from oa_fin_payment_record where deleted=0 and owner_id=?),0)  where id=?",id,id);
			FinPaymentNoTicket finPaymentNoTicket=finPaymentNoTicketService.getById(id);
			BigDecimal paymentAmount=finPaymentNoTicket.getPaymentAmount();
			BigDecimal totalAmount=finPaymentNoTicket.getAmount();
			if("finish".equals(actionType)){
				if(totalAmount.compareTo(paymentAmount)==0){
					finPaymentNoTicket.setPaymentStatus(FinPaymentStatusEnum.FINISH.code());
					finPaymentNoTicketService.update(finPaymentNoTicket,SaveMode.NOT_NULL_FIELDS);
				}else{
					return ErrorDesc.failureMessage("当前没有全部完成支付");
				}
			}else if("part_finish".equals(actionType)){
				finPaymentNoTicket.setPaymentStatus(FinPaymentStatusEnum.PART_FINISH.code());
				finPaymentNoTicketService.update(finPaymentNoTicket,SaveMode.NOT_NULL_FIELDS);
			}else{
				ErrorDesc.failureMessage("错误的动作类型");
			}
		} else if ("ticket".equals(ownerType)) {
			dao.execute("update oa_fin_collect_ticket set payment_amount=ifnull((select sum(amount) from oa_fin_payment_record where deleted=0 and owner_id=?),0)  where id=?", id,id);
			FinCollectTicket finCollectTicket=finCollectTicketService.getById(id);
			BigDecimal paymentAmount=finCollectTicket.getPaymentAmount();
			BigDecimal totalAmount=finCollectTicket.getAmount();
			if("finish".equals(actionType)){
				if(totalAmount.compareTo(paymentAmount)==0){
					finCollectTicket.setPaymentStatus(FinPaymentStatusEnum.FINISH.code());
					finCollectTicketService.update(finCollectTicket,SaveMode.NOT_NULL_FIELDS);
				}else{
					return ErrorDesc.failureMessage("当前没有全部完成支付");
				}
			}else if("part_finish".equals(actionType)){
				finCollectTicket.setPaymentStatus(FinPaymentStatusEnum.PART_FINISH.code());
				finCollectTicketService.update(finCollectTicket,SaveMode.NOT_NULL_FIELDS);
			}else{
				ErrorDesc.failureMessage("错误的动作类型");
			}
		}

		return ErrorDesc.success();
	}

	/**
	 * 添加，如果语句错误，则抛出异常
	 * @param finPaymentRecord 数据对象
	 * @return 插入是否成功
	 * */
	@Override
	public Result insert(FinPaymentRecord finPaymentRecord) {
		return this.insert(finPaymentRecord,true);
	}

	/**
	 * 批量插入实体，事务内
	 * @param finPaymentRecordList 实体数据清单
	 * @return 插入是否成功
	 * */
	@Override
	public Result insertList(List<FinPaymentRecord> finPaymentRecordList) {
		return super.insertList(finPaymentRecordList);
	}

	
	/**
	 * 按主键删除付款记录
	 *
	 * @param id 主键
	 * @return 删除是否成功
	 */
	public Result deleteByIdPhysical(String id) {
		FinPaymentRecord finPaymentRecord = new FinPaymentRecord();
		if(id==null) return ErrorDesc.failure().message("id 不允许为 null 。");
		finPaymentRecord.setId(id);
		try {
			FinPaymentRecord source = this.getById(id);
			boolean suc = dao.deleteEntity(finPaymentRecord);
			if(suc){
				if("no_ticket".equals(source.getOwnerType())){
					dao.execute("update oa_fin_payment_no_ticket set payment_amount=ifnull((select sum(amount) from oa_fin_payment_record where deleted=0 and owner_id=?),0)  where id=?",source.getOwnerId(),source.getOwnerId());
				}else if("ticket".equals(source.getOwnerType())){
					dao.execute("update oa_fin_collect_ticket set payment_amount=ifnull((select sum(amount) from oa_fin_payment_record where deleted=0 and owner_id=?),0) where id=?",source.getOwnerId(),source.getOwnerId());
				}
			}
			return suc?ErrorDesc.success():ErrorDesc.failure();
		}
		catch(Exception e) {
			Result r= ErrorDesc.failure();
			r.extra().setException(e);
			return r;
		}
	}
	
	/**
	 * 按主键删除付款记录
	 *
	 * @param id 主键
	 * @return 删除是否成功
	 */
	public Result deleteByIdLogical(String id) {
		FinPaymentRecord finPaymentRecord = new FinPaymentRecord();
		if(id==null) return ErrorDesc.failure().message("id 不允许为 null 。");
		finPaymentRecord.setId(id);
		finPaymentRecord.setDeleted(true);
		finPaymentRecord.setDeleteBy((String)dao.getDBTreaty().getLoginUserId());
		finPaymentRecord.setDeleteTime(new Date());
		try {
			FinPaymentRecord source = this.getById(id);
			boolean suc = dao.updateEntity(finPaymentRecord,SaveMode.NOT_NULL_FIELDS);
			if(suc){
				if("no_ticket".equals(source.getOwnerType())){
					dao.execute("update oa_fin_payment_no_ticket set payment_amount=ifnull((select sum(amount) from oa_fin_payment_record where deleted=0 and owner_id=?),0) where id=?",source.getOwnerId(),source.getOwnerId());
				}else if("ticket".equals(source.getOwnerType())){
					dao.execute("update oa_fin_collect_ticket set payment_amount=ifnull((select sum(amount) from oa_fin_payment_record where deleted=0 and owner_id=?),0)  where id=?",source.getOwnerId(),source.getOwnerId());
				}
			}
			return suc?ErrorDesc.success():ErrorDesc.failure();
		}
		catch(Exception e) {
			Result r= ErrorDesc.failure();
			r.extra().setException(e);
			return r;
		}
	}

	/**
	 * 更新，如果执行错误，则抛出异常
	 * @param finPaymentRecord 数据对象
	 * @param mode 保存模式
	 * @return 保存是否成功
	 * */
	@Override
	public Result update(FinPaymentRecord finPaymentRecord , SaveMode mode) {
		return this.update(finPaymentRecord,mode,true);
	}

	/**
	 * 更新，根据 throwsException 参数抛出异常或返回 Result 对象
	 * @param finPaymentRecord 数据对象
	 * @param mode 保存模式
	 * @param throwsException 是否抛出异常，如果不抛出异常，则返回一个失败的 Result 对象
	 * @return 保存是否成功
	 * */
	@Override
	public Result update(FinPaymentRecord finPaymentRecord , SaveMode mode,boolean throwsException) {
		BigDecimal totalAmount=null;
		BigDecimal paymentAmount=null;
		FinPaymentRecord sourceRecord=this.getById(finPaymentRecord.getId());
		if("no_ticket".equals(finPaymentRecord.getOwnerType())){
			FinPaymentNoTicket finPaymentNoTicket=finPaymentNoTicketService.getById(finPaymentRecord.getOwnerId());
			paymentAmount=finPaymentNoTicket.getPaymentAmount();
			totalAmount=finPaymentNoTicket.getAmount();
			if(FinPaymentStatusEnum.PART.code().equals(finPaymentNoTicket.getPaymentStatus())
					||FinPaymentStatusEnum.WAIT.code().equals(finPaymentNoTicket.getPaymentStatus())){
				Logger.info("ticket");
			}else{
				return ErrorDesc.failureMessage("当前单据状态无法进行付款操作");
			}
		}else if("ticket".equals(finPaymentRecord.getOwnerType())){
			FinCollectTicket finCollectTicket=finCollectTicketService.getById(finPaymentRecord.getOwnerId());
			paymentAmount=finCollectTicket.getPaymentAmount();
			totalAmount=finCollectTicket.getAmount();
			if(FinPaymentStatusEnum.PART.code().equals(finCollectTicket.getPaymentStatus())
					||FinPaymentStatusEnum.WAIT.code().equals(finCollectTicket.getPaymentStatus())){
				Logger.info("ticket");
			}else{
				return ErrorDesc.failureMessage("当前单据状态无法进行付款操作");
			}
		}else{
			return ErrorDesc.failureMessage("当前类型不正确,类型:"+finPaymentRecord.getOwnerType());
		}

		if(finPaymentRecord.getAmount().compareTo(BigDecimal.ZERO)<=0){
			return ErrorDesc.failureMessage("金额必须大于0");
		}

		if(finPaymentRecord.getAmount().compareTo(totalAmount)>0){
			return ErrorDesc.failureMessage("金额必须小于"+totalAmount+"元");
		}

		if(!SessionUser.getCurrent().getActivatedEmployeeId().equals(sourceRecord.getOriginatorId())){
			return ErrorDesc.failureMessage("当前操作人员和原操作人员不一致");
		}


		if(finPaymentRecord.getAmount().add(paymentAmount).divide(sourceRecord.getAmount()).compareTo(totalAmount)>0){
			return ErrorDesc.failureMessage("总金额为:"+totalAmount+",当前支付总金额:"+finPaymentRecord.getAmount().add(paymentAmount)+",已超额支付");
		}


		Result r=super.update(finPaymentRecord , mode , throwsException);

		if(r.isSuccess()) {
			//开始更新主要单据
			if ("no_ticket".equals(finPaymentRecord.getOwnerType())) {
				FinPaymentNoTicket finPaymentNoTicket = new FinPaymentNoTicket();
				finPaymentNoTicket.setPaymentLastDate(new Date());
				finPaymentNoTicket.setId(finPaymentRecord.getOwnerId());
				finPaymentNoTicket.setPaymentStatus(FinPaymentStatusEnum.PART.code());
				finPaymentNoTicketService.update(finPaymentNoTicket, SaveMode.NOT_NULL_FIELDS);
				//计算
				dao.execute("update oa_fin_payment_no_ticket set payment_amount=ifnull((select sum(amount) from oa_fin_payment_record where deleted=0 and owner_id=?),0)  where id=?", finPaymentRecord.getOwnerId(), finPaymentRecord.getOwnerId());
			} else if ("ticket".equals(finPaymentRecord.getOwnerType())) {
				FinCollectTicket finCollectTicket = new FinCollectTicket();
				finCollectTicket.setPaymentTime(new Date());
				finCollectTicket.setId(finPaymentRecord.getOwnerId());
				finCollectTicket.setPaymentStatus(FinPaymentStatusEnum.PART.code());
				finCollectTicketService.update(finCollectTicket, SaveMode.NOT_NULL_FIELDS);
				//计算
				dao.execute("update oa_fin_collect_ticket set payment_amount=ifnull((select sum(amount) from oa_fin_payment_record where deleted=0 and owner_id=?),0)  where id=?", finPaymentRecord.getOwnerId(), finPaymentRecord.getOwnerId());
			}
		}


		return r;
	}

	/**
	 * 更新实体集，事务内
	 * @param finPaymentRecordList 数据对象列表
	 * @param mode 保存模式
	 * @return 保存是否成功
	 * */
	@Override
	public Result updateList(List<FinPaymentRecord> finPaymentRecordList , SaveMode mode) {
		return super.updateList(finPaymentRecordList , mode);
	}

	
	/**
	 * 按主键更新付款记录
	 *
	 * @param id 主键
	 * @return 是否更新成功
	 */
	public boolean update(DBField field,Object value , String id) {
		if(id==null) throw new IllegalArgumentException("id 不允许为 null ");
		if(!field.table().name().equals(this.table())) throw new IllegalArgumentException("更新的数据表["+field.table().name()+"]与服务对应的数据表["+this.table()+"]不一致");
		int suc=dao.update(field.table().name()).set(field.name(), value).where().and("id = ? ",id).top().execute();
		return suc>0;
	}

	
	/**
	 * 按主键获取付款记录
	 *
	 * @param id 主键
	 * @return FinPaymentRecord 数据对象
	 */
	public FinPaymentRecord getById(String id) {
		FinPaymentRecord sample = new FinPaymentRecord();
		if(id==null) throw new IllegalArgumentException("id 不允许为 null ");
		sample.setId(id);
		return dao.queryEntity(sample);
	}

	/**
	 * 等价于 queryListByIds
	 * */
	@Override
	public List<FinPaymentRecord> getByIds(List<String> ids) {
		return this.queryListByIds(ids);
	}

	@Override
	public List<FinPaymentRecord> queryListByIds(List<String> ids) {
		return super.queryListByUKeys("id",ids);
	}

	@Override
	public Map<String, FinPaymentRecord> queryMapByIds(List<String> ids) {
		return super.queryMapByUKeys("id",ids, FinPaymentRecord::getId);
	}



	/**
	 * 查询实体集合，默认情况下，字符串使用模糊匹配，非字符串使用精确匹配
	 *
	 * @param sample  查询条件
	 * @return 查询结果
	 * */
	@Override
	public List<FinPaymentRecord> queryList(FinPaymentRecordVO sample) {
		return super.queryList(sample);
	}


	/**
	 * 分页查询实体集，字符串使用模糊匹配，非字符串使用精确匹配
	 *
	 * @param sample  查询条件
	 * @param pageSize 分页条数
	 * @param pageIndex 页码
	 * @return 查询结果
	 * */
	@Override
	public PagedList<FinPaymentRecord> queryPagedList(FinPaymentRecordVO sample, int pageSize, int pageIndex) {
		return super.queryPagedList(sample, pageSize, pageIndex);
	}

	/**
	 * 分页查询实体集，字符串使用模糊匹配，非字符串使用精确匹配
	 *
	 * @param sample  查询条件
	 * @param condition 其它条件
	 * @param pageSize 分页条数
	 * @param pageIndex 页码
	 * @return 查询结果
	 * */
	@Override
	public PagedList<FinPaymentRecord> queryPagedList(FinPaymentRecord sample, ConditionExpr condition, int pageSize, int pageIndex) {
		return super.queryPagedList(sample, condition, pageSize, pageIndex);
	}

	/**
	 * 检查 实体 是否已经存在 , 判断 主键值不同，但指定字段的值相同的记录是否存在
	 *
	 * @param finPaymentRecord 数据对象
	 * @return 判断结果
	 */
	public Boolean checkExists(FinPaymentRecord finPaymentRecord) {
		//TDOD 此处添加判断段的代码
		//boolean exists=super.checkExists(finPaymentRecord, SYS_ROLE.NAME);
		//return exists;
		return false;
	}

	/**
	 * 批量检查引用
	 * @param ids  检查这些ID是否又被外部表引用
	 * */
	@Override
	public <T> Map<T, ReferCause> hasRefers(List<T> ids) {
		// 默认无业务逻辑，返回此行；有业务逻辑需要校验时，请修改并使用已注释的行代码！！！
		return MapUtil.asMap(ids,new ReferCause(false));
		// return super.hasRefers(FoxnicWeb.BPM_PROCESS_INSTANCE.FORM_DEFINITION_ID,ids);
	}





}